#if UNITY_WEBGL
using System;
using System.Runtime.InteropServices;
using AOT;
#endif
using UnityEngine;

namespace CGF
{
    public class CopyAndPaste
    {
        private static CTask<string> getPasteTask;

#if UNITY_WEBGL
        private delegate void Callback(IntPtr dbNamePtr);
        [DllImport("__Internal")]
        private static extern void Web_Init();
        [DllImport("__Internal")]
        private static extern void Web_Copy(string content);
        [DllImport("__Internal")]
        private static extern void Web_GetPaste(Callback callback);
#endif

        // 辅助方法：将字符串转换为字节数组进行复制
        public static void Copy(string content)
        {
            if (Define.IsWebGL && !Application.isEditor)
            {
#if UNITY_WEBGL
                Web_Init();
                Web_Copy(content);
#endif
            }
            else
            {
                GUIUtility.systemCopyBuffer = content;
            }
        }

        // 辅助方法：将获取的字节数组转换为字符串
        public static async CTask<string> GetPaste()
        {
            getPasteTask = CTask<string>.Create();
            if (Define.IsWebGL && !Application.isEditor)
            {
#if UNITY_WEBGL
                Web_Init();
                Web_GetPaste(GetPasteContentCallback);
#endif
            }
            else
            {
                getPasteTask.SetResult(GUIUtility.systemCopyBuffer);
            }
            return await getPasteTask;
        }

#if UNITY_WEBGL
        [MonoPInvokeCallback(typeof(Callback))]
        private static void GetPasteContentCallback(IntPtr contentPtr)
        {
            if (getPasteTask == null) return;
            try
            {
                if (contentPtr == IntPtr.Zero)
                {
                    getPasteTask.SetResult("");
                }
                string result = Marshal.PtrToStringAnsi(contentPtr);
                Marshal.FreeHGlobal(contentPtr);
                getPasteTask.SetResult(result ?? "");
            }
            catch (Exception e)
            {
                getPasteTask.SetResult(e.Message);
            }
        }
#endif
    }
}
